import { DeviceBindDeleteData, GetDeviceBind, GetDeviceBindById, GetUserInfo, PostDeviceBind } from "/constData/requestFun/_teseRequest";
import compact from 'loadsh/compact'
import { GetUserInfoFiled } from "/constData/requestFun/_utils";
Page({
  data: {
    devicebindinfo: [
    ],
    ReceiveData: [],
  },
  onNumberChange(val, e) {
    const n = e.target.dataset.name
    const d = []
    this.data.devicebindinfo.forEach((data) => {
      if (data.name === n) {
        d.push({ ...data, equipmentId: val })
      } else {
        d.push({ ...data })
      }
    })
    this.setData({
      devicebindinfo: d
    })
  },
  //获取数据
  onLoad() {
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        new Promise((resolveOuter) => {
          GetDeviceBind((item) => {
            const promises = item.data.map((dataItem) => {
              return new Promise((resolveInner) => {
                GetUserInfo(
                  {
                    userId: dataItem.item1.userId,
                    fileds: null
                  },
                  (userInfoResult) => {
                    const name = GetUserInfoFiled(userInfoResult, 'name');
                    resolveInner({ ...dataItem, item1: { ...dataItem.item1, name } });
                  }
                );
              });
            });
            Promise.all(promises).then((updatedDataItems) => {
              this.setData({ ReceiveData: updatedDataItems });
              resolveOuter(updatedDataItems); // 这里可以根据需要调整，例如返回所有名字  
            });
          });
        }).then((updatedDataItems) => {
        }).catch((error) => {
          // 处理任何可能出现的错误  
          console.error('An error occurred:', error);
        });
      }
    })
  },
  onSubmit() {
    const processedData = this.data.devicebindinfo.map(item => ({
      equipmentId: item.equipmentId,
      userId: item.userId
    }));
    for (let index = 0; index < processedData.length; index++) {
      PostDeviceBind((JSON.stringify(processedData[index])), res => {
        if (index === processedData.length - 1) {
          my.alert({
            title: '保存成功',
          });
        }
        GetDeviceBind((item) => {
          const promises = item.data.map((dataItem) => {
            return new Promise((resolveInner) => {
              GetUserInfo(
                {
                  userId: dataItem.item1.userId,
                  fileds: null
                },
                (userInfoResult) => {
                  const name = GetUserInfoFiled(userInfoResult, 'name');
                  resolveInner({ ...dataItem, item1: { ...dataItem.item1, name } });
                }
              );
            });
          });
          Promise.all(promises).then((updatedDataItems) => {
            this.setData({ ReceiveData: updatedDataItems });
          });
        });
      })
    }
  },
  Del(e) {
    const n = e.target.dataset.name
    this.setData({
      devicebindinfo:
        this.data.devicebindinfo.filter((p) => {
          return p.name !== n
        })

    })
  },
  DelUserId(e) {
    const id = e.target.dataset.id
    DeviceBindDeleteData(id, (res) => {
      new Promise((resolveOuter) => {
        GetDeviceBind((item) => {
          const promises = item.data.map((dataItem) => {
            return new Promise((resolveInner) => {
              GetUserInfo(
                {
                  userId: dataItem.item1.userId,
                  fileds: null
                },
                (userInfoResult) => {
                  const name = GetUserInfoFiled(userInfoResult, 'name');
                  resolveInner({ ...dataItem, item1: { ...dataItem.item1, name } });
                }
              );
            });
          });
          Promise.all(promises).then((updatedDataItems) => {
            this.setData({ ReceiveData: updatedDataItems });
            resolveOuter(updatedDataItems); // 这里可以根据需要调整，例如返回所有名字  
          });
        });
      })
      my.alert({
        title: '删除成功',
      });
    })
  },
  // 选择绑定人
  SelectBinder() {
    my.complexChoose({
      title: "测试标题", //标题
      multiple: true, //是否多选
      limitTips: "超出了", //超过限定人数返回提示
      maxUsers: 1000, //最大可选人数
      responseUserOnly: false, //返回人，或者返回人和部门
      success: (res) => {
        for (let index = 0; index < res.users.length; index++) {
          this.setData({
            devicebindinfo: [
              ...this.data.devicebindinfo,
              { ...res.users[index], equipmentId: "未绑定" },
            ]
          })
        }
      },
      fail: function (err) { }
    })
  },
});


